
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>数据字典管理</title>
    <script type="text/javascript" src="../../lib/innerIframe-include-ext.js"></script>
    <script type="text/javascript" src="../../lib/loader-theme.js"></script>
    <script type="text/javascript" src="../../lib/myext_common.js"></script>
    <script type="text/javascript" src="../../lib/ext/locale/ext-lang-zh_CN.js"></script>
    <script type="text/javascript" src="../../lib/ext/plugins/DataTip.js"></script>
    <script type="text/javascript" src="../../lib/commonUtil.js"></script>
    <script type="text/javascript" src="../../js/moment.min.js"></script>
</head>
<script type="text/javascript">
Ext.Loader.setConfig({
    enabled: true
});

Ext.Loader.setPath('Ext.ux', '/ext4/ux/');
Ext.require([
    'Ext.grid.*',
    'Ext.data.*',
    'Ext.util.*',
    'Ext.toolbar.Paging',
    'Ext.ModelManager',
    'Ext.tip.QuickTipManager'
]);
var win, searchForm;
var parent_id = 0;
Ext.onReady(function() {

    Ext.define('Dict', {
        extend: 'Ext.data.Model',
        fields: [
            'id', 'key_code', 'key_name', 'parent_id', 'key_desc','sorder','create_at','update_at'
        ],
        idProperty: 'id'
    });

    var store = Ext.create('Ext.data.Store', {
        pageSize: 20,
        model: 'Dict',
        remoteSort: true,
        proxy: {
            type: 'ajax',
            url: '/dict/list',
            reader: {
                type: 'json',
                root: 'data',
                totalProperty: 'count'
            },
            simpleSortMode: true
        },
        sorters: [{
            property: 'sorder',
            direction: 'ASC'
        }]
    });

    var grid = Ext.create('Ext.grid.Panel', {
        store: store,
        loadMask: true,
        region: 'center',
        selModel: Ext.create('Ext.selection.CheckboxModel'),
        columns: [{
            text:'parent_id',
            dataIndex:'parent_id',
            hidden: true
        },{
            text: "字典id",
            width: 75,
            dataIndex: 'id',
            hidden: true
        }, {
            text: '字典名称',
            dataIndex: 'key_name',
            sortable:true,
            width : '15%'
        }, {
            text: '字典编码',
            dataIndex: 'key_code',
            sortable:true,
            width : '15%'
        }, {
            text: '排序',
            dataIndex: 'sorder',
            width : '80'
        }, {
            text: '字典备注',
            dataIndex: 'key_desc',
            width : '30%'
        },{
            text: '创建时间',
            dataIndex:'create_at',
            renderer:function(val) {
                if(val) return moment(val).format('YYYY-MM-DD');
            }
        },{
            text: '更新时间',
            dataIndex:'update_at',
            renderer:function(val) {
                if(val) return moment(val).format('YYYY-MM-DD');
            }
        }],
        // paging bar on the bottom
        bbar: Ext.create('Ext.PagingToolbar', {
            store: store,
            displayInfo: true,
            displayMsg: 'Displaying {0} - {1} of {2}',
            emptyMsg: "没有数据！！！"
        }),
        tbar: [
        {
            icon: '../../img/add.png',
            text: "添  加",
            handler: addDict
        }, {
            text: "修  改",
            icon: '../../img/edit.png',
            handler: updDict
            // function() {
            //     doEdit("dict_id",grid, "./add.html", "修改字典")
            // }
        }, {
            icon: '../../img/delete.png',
            text: "删  除",
            handler: function() {
                var orows = grid.getSelectionModel().getSelection();
                if (orows.length == 0) {
                    Ext.MessageBox.alert('消息提示', '请选择一条记录！');
                    return;
                }
                if(orows.length > 1) {
                    Ext.MessageBox.alert('消息提示', '不允许批量删除！');
                    return;
                }
                Ext.MessageBox.confirm('消息提示', '确定删除对象？', function(btn) {
                    if (btn == "yes") {
                        Ext.Ajax.request({
                            url: '/dict/delete',
                            params: {
                                id: orows[0].get('id'),
                                key_code: orows[0].get('key_code')
                            },
                            method: 'POST',
                            success: function(response, options) {
                                Ext.MessageBox.alert('消息提示', '删除成功！');
                                store.loadPage(1);
                                refreshResTree('/dict/tree', tree);
                            },
                            failure: function(response, options) {
                                // Ext.MessageBox.alert('消息提示', '操作失败！');
                                Ext.MessageBox.alert('消息提示', Ext.JSON.decode(response.responseText).error);
                            }
                        });
                    }
                })
            }
        },{
            xtype:'textfield',
            labelAlgin:'right',
            labelWidth:60,
            width:200,
            fieldLabel: '字典名称',
            name: 'key_name',
            id:'key_name',
            allowBlank: true
        }, {
            xtype:'textfield',
            labelAlgin:'right',
            labelWidth:60,
            width:200,
            fieldLabel: '字典编码',
            maxLength:32,
            name: 'key_code',
            id:'key_code',
            allowBlank: true
        },{
            text: '搜  索',
            icon : '../../img/search.png',
            handler: doSearch
        }]
    });

    store.on('beforeload', function(store, operation, eOpts) {
        //operation.params = searchForm.getValues();
        var proxy = store.getProxy();
        proxy.extraParams = {
            parent_id:parent_id   
        };
    }, this);

    var tree = Ext.create('Ext.tree.Panel', {
        autoWidth:true,
        autoHeight:true,
        rootVisible: true,
        listeners:{
            'itemclick':function(view, record, item, index, e, eOpts){
                parent_id = record.get('id');
                store.loadPage(1,{params:{parent_id:parent_id}});
            }
        }
    });

    function doSearch(){
        var params  = {};
        params.key_name = Ext.getCmp('key_name').getValue();
        params.key_code = Ext.getCmp('key_code').getValue();
        store.loadPage(1,{params:params});
    }

    var addWin;
    var dataForm = new Ext.FormPanel({
        url:'/dict/add',
        method:'POST',
        frame:true,
        bodyBorder:false,
        bodyPadding:'20 20 0',
        layout:'form',
        plugins: {
            ptype: 'datatip'
        },
        fieldDefaults: {
            msgTarget: 'side',
            labelWidth: 60
        },
        defaults:{
            labelAlign:'right'
        },
        items:[{
            xtype:'hidden',
            name:'id',
            id:'dict_id'
        },{
            xtype:'hidden',
            name:'parent_id',
            id:'parent_id',
            value:parent_id
        },{
            xtype:'textfield',
            fieldLabel:'字典名称',
            tooltip:'请输入字典名称',
            id:'form_key_name',
            name:'key_name',
            maxLength:30,
            allowBlank:false
        },{
            xtype:'textfield',
            fieldLabel:'字典编码',
            allowBlank:false,
            maxLength:30,
            name:'key_code',
            id:'form_key_code',
            validateOnChange:false, 
            validator:function(){
                var _value = this.getValue();
                var dict_id = Ext.getCmp('dict_id').getValue();
                var _flag = true;
                //仅添加时才验证
                //alert(dataForm.getForm().url);
                //if(dataForm.getForm().url=='/dict/add'){
                Ext.Ajax.request({
                    async:false,
                    url: '/dict/check?dict_id='+dict_id+'&key_code='+_value,
                    method : 'GET',
                    scope : this,// 如果通过 ajax 访问后台数据记得要加 async:false 同步
                    success: function(response, opts) {
                        var data = eval("("+response.responseText+")");
                        _flag = data.success;
                    },
                    failure: function(response, opts) {
                        var data = eval("("+response.responseText+")");
                        if(!data.success){
                            Ext.Msg.alert('信息提示',data.msg);
                        } else {
                            Ext.Msg.alert("信息提示","系统忙，请稍候再试");
                        }
                    }
                });
                if (!_flag) {
                    return true;
                } else {
                    //this.markInvalid("此编码已经存在！");
                    //Ext.Msg.alert('错误提示', '此编码已经存在！');
                    return "此编码已经存在！";
                }
                //} else {
                    //return true;
                //}
            }
        },{
            xtype:'textarea',
            fieldLabel:'字典描述',
            allowBlank:true,
            name:'key_desc',
            id:'key_desc',
            maxLength:200 
        },{
            xtype:'combo',
            fieldLabel:'显示顺序',
            allowBlank:true,
            name:'sorder',
            id:'sorder',
            allowBlank:false,
            regex : /^[0-9]*$/,
            regexText:'只能是数字',
            store: Ext.create('Ext.data.Store', {
                fields: ['num', 'num'],
                data : []
            }),
            queryMode: 'local',
            width:80,
            displayField: 'num',
            valueField: 'num'
        }],
        buttons:[{ 
            text:'保  存',
            icon:'../../img/accept.png',
            handler:function(){
                if(!dataForm.getForm().isValid()){
                     Ext.Msg.alert('信息提示','请检查输入项是否按要求填写！');
                     return;
                }
                if(Ext.getCmp('form_key_name').getValue().replace(/\s+/g,"") == ''){
                    Ext.Msg.alert('信息提示','字典名称不能为空！');
                    return;
                }
                if(Ext.getCmp('form_key_code').getValue().replace(/\s+/g,"") == ''){
                    Ext.Msg.alert('信息提示','字典编码不能为空！');
                    return;
                }
                var formValues = dataForm.form.getValues();
                dataForm.form.submit({
                    waitMsg:'正在保存数据...',
                    success:function(form,action){
                        if(action.result.success){
                            if(dataForm.getForm().url=='/dict/add'){
                                Ext.Msg.alert('信息提示','添加成功！');
                            } else {
                                Ext.Msg.alert('信息提示','修改成功！');
                            }
                            store.reload();
                            //还需要刷新资源树
                            refreshResTree('/dict/tree', tree);
                            dataForm.form.reset();
                            addWin.hide();
                        } else {
                            Ext.Msg.alert('信息提示',action.result.msg);
                        }
                    },
                    failure:function(form,action){
                        var result = Ext.decode(action.response.responseText);
                        if(!result.success){
                            Ext.Msg.alert('信息提示',result.msg);
                        } else {
                            Ext.Msg.alert('信息提示','操作失败，请重试！');
                        }
                    }
                });
            }
        },{
            text:'关  闭',
            icon:'../../img/close.png',
            handler:function(){
                this.up('form').getForm().reset();
                addWin.hide();
            }
        }]
    });
    function addDict(){
        if(!addWin){
            addWin = Ext.create('Ext.Window', {
                title: '添加字典信息',
                width: 400,
                height: 300,
                bodyPadding: '0 0 0',
                constrainHeader: true,
                closeAction:'hide',
                layout: 'fit',
                items: dataForm
            });
        }
        dataForm.getForm().url='/dict/add';
        Ext.getCmp('parent_id').setValue(parent_id);
        //设置显示顺序
        loadSort('add', dataForm, store);
        Ext.getCmp('sorder').setValue(store.getTotalCount()+1);
        addWin.show();
    }
    function updDict(){
        var records = grid.getSelectionModel().getSelection();
        if(records.length > 1){
            Ext.Msg.alert("信息提示","只能选择一条数据进行修改！");
            return;
        } 
        if(records.length == 0){
            Ext.Msg.alert("信息提示","请选择需要修改的数据！");
            return;
        }
        if(!addWin){
            addWin = Ext.create('Ext.Window', {
                title: '修改字典信息',
                width: 400,
                height: 300,
                bodyPadding: '0 0 0',
                'z-index': 9999999,
                constrainHeader: true,
                closeAction:'hide',
                layout: 'fit',
                items: dataForm
            });
        }
        dataForm.getForm().url='/dict/edit';
        //dataForm.form.loadRecord(records[0]);
        Ext.Ajax.request({
            url: '/dict/detail',
            params : {'id' : records[0].get('id')},
            method : 'get',
            success: function(response, opts) {
                var jsonResult = Ext.decode(response.responseText); 
                if(jsonResult.success == false){
                    return alert(jsonResult.error || jsonResult.msg);
                }
                if(!jsonResult){
                    return ;
                }
                for(var i in jsonResult){
                    if(dataForm.form.findField(i)){
                        dataForm.form.findField(i).setValue(jsonResult[i]);
                    }
                }
                addWin.show();
            }
        });
        //设置当前操作数据的父Id
        //Ext.getCmp('parent_id').setValue(parent_id);
        //设置显示顺序
        //loadSort('upd', dataForm, store);
        //Ext.getCmp('sorder').setValue(records[0].get('sorder'));
    }
    
    function del_res(){
        var records = grid.getSelectionModel().getSelection();
        if(records.length == 0){
            Ext.Msg.alert("信息提示","请选择需要删除的数据！");
            return;
        }
        if(records.length > 1){
            Ext.Msg.alert("信息提示","每次仅允许删除一条数据！");
            return;
        }
        Ext.MessageBox.confirm('信息提示','确认删除吗？',function(val){
            if(val == 'yes'){
                Ext.Ajax.request({
                    url: '/dict/delete?id'+records[0].get('id'),
                    method : 'POST',
                    success: function(response, opts) {
                        var data = eval("("+response.responseText+")");
                        if(data.success){
                            Ext.Msg.alert('信息提示',data.msg,function(){
                                store.reload();
                                refreshResTree('/dict/tree', tree);
                            });
                        } else {
                            Ext.Msg.alert('信息提示',data.msg);
                        }
                    },
                    failure: function(response, opts) {
                        var data = eval("("+response.responseText+")");
                        if(!data.success){
                            Ext.Msg.alert('信息提示',data.msg);
                        } else {
                            Ext.Msg.alert("信息提示","网络错误，请稍候再试");
                        }
                    }
                });
            }
        });
    }

    // store.on('beforeload', function(store, operation, eOpts) {
    //     //operation.params = searchForm.getValues();
    // }, this);
    //store.loadPage(1);

    var viewport = Ext.create('Ext.Viewport', {
        id: 'border-example',
        layout: 'border',//框式布局
        items: [
             {
                region: 'west',
                stateId: 'navigation-panel',
                id: 'west-panel',
                border:false,
                title: '字典树结构',
                split: true,
                width: 250,
                collapsible: true,
                margins: '0 0 0 5',
                layout: 'fit',
                items: tree
            },grid
           ]
    });

    //初始化表格数据
    store.loadPage(1);
    //初始化资源树root信息
    refreshResTree('/dict/tree', tree); 
});
</script>
<body>
</body>
</html>